<!-- ERP 产品列表 -->
<template>
  <doc-alert title="【产品】产品信息、分类、单位" url="https://doc.iocoder.cn/erp/product/" />

  <ContentWrap>
    <!-- 搜索工作栏 :filter-method="hospitalFilter" -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="名称" prop="id">
        <!-- remote远程搜索组件  将select选择器改为输入框  :filter-method 键入监听方法    filterable 键入组件 -->
        <el-select
          v-model="queryParams.id"
          clearable
          remote
          :filter-method="hospitalFilter"
          filterable
          placeholder="请选择产品名称"
          class="!w-240px"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.fullName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          clearable
          :data="categoryList"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请输入分类"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="单位" prop="unitId">
        <el-tree-select
          v-model="queryParams.unitId"
          clearable
          :data="unitList"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请输入单位"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="生产厂家" prop="manufacturer">
        <el-input
          v-model="queryParams.manufacturer"
          placeholder="请输入生产厂家"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否带量" prop="isQuantity">
        <el-select
          v-model="queryParams.isQuantity"
          placeholder="请选择是否带量"
          clearable
          class="!w-240px"
        >
        <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_IS_QUANTITY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否收费" prop="isFree">
        <el-select
          v-model="queryParams.isFree"
          placeholder="请选择是否收费"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.IS_FREE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专机专用" prop="isDedicated">
        <el-select
          v-model="queryParams.isDedicated"
          placeholder="请选择是否专机专用"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.IS_DEDICATED)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="注册证号" prop="registCertNum">
        <el-input
          v-model="queryParams.registCertNum"
          placeholder="请输入注册证号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="医保编码" prop="medicalInsurCode">
        <el-input
          v-model="queryParams.medicalInsurCode"
          placeholder="请输入医保27位编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['spd:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['spd:product:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="条码" align="center" prop="barCode" width="200%"/>
      <el-table-column label="名称" align="center" prop="name" width="200%"/>
      <el-table-column label="规格" align="center" prop="standard" width="100%"/>
      <el-table-column label="分类" align="center" prop="categoryName" width="100%"/>
      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="生产厂家" align="center" prop="manufacturer" width="200%"/>
      <el-table-column label="是否收费" align="center" prop="isFree"  >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IS_FREE" :value="scope.row.isFree" />
        </template>
      </el-table-column>
      <el-table-column label="专机专用" align="center" prop="isDedicated"  width="150%">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IS_DEDICATED" :value="scope.row.isDedicated" />
        </template>
      </el-table-column>
      <el-table-column label="注册证号" align="center" prop="registCertNum" />
      <el-table-column label="医保编码" align="center" prop="medicalInsurCode" width="300%"/>
      <el-table-column
      label="生效日期"
      align="center"
      prop="startTime"
      :formatter="dateFormatter"
      width="180px"
    />
      <el-table-column
        label="采购价格"
        align="center"
        prop="purchasePrice"
        :formatter="erpPriceTableColumnFormatter"
         width="100px"
      />
      <!-- <el-table-column
        label="销售价格"
        align="center"
        prop="salePrice"
        :formatter="erpPriceTableColumnFormatter"
         width="100px"
      /> -->
      <!-- <el-table-column
        label="最低价格"
        align="center"
        prop="minPrice"
        :formatter="erpPriceTableColumnFormatter"
        width="100px"
      /> -->
      <el-table-column label="状态" align="center" prop="status"  >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="是否带量" align="center" prop="isQuantity"  width="150%">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_IS_QUANTITY" :value="scope.row.isQuantity" />
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200%">
        <template #default="scope">
          <!-- 列表操作列中的按钮 -->
            <el-button
              link
              type="primary"
              @click="openPriceForm('adjustPrice', scope.row.dataId)"
              v-hasPermi="['spd:product:update']"
            >
              调价
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.dataId)"
            v-hasPermi="['spd:product:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.dataId)"
            v-hasPermi="['spd:product:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ProductForm ref="formRef" @success="getList" />
  <!-- 新增调价弹窗 -->
  <ProductPriceForm ref="priceFormRef" @success="getList" />
</template>

<script setup lang="ts">
import ProductPriceForm from './ProductPriceForm.vue'
//引入全局方法  防抖
import debounce from 'lodash/debounce'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
//产品查询API和实体
import { ProductApi, ProductVO } from '@/api/spd/product/product'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/spd/product/category'
import { ProductUnitApi, ProductUnitVO } from '@/api/spd/product/unit'
import ProductForm from './ProductForm.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import { erpPriceTableColumnFormatter } from '@/utils'
/** ERP 产品列表 */
defineOptions({ name: 'ErpProduct' })
const supplierList = ref<ProductVO[]>([])  // 供应商列表
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const list = ref<ProductVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  manufacturer: undefined,
  id:undefined,
  fullPinyin:undefined,
  isFree: undefined,
  firstPinyin:undefined,
  isDedicated: undefined,
  registCertNum: undefined,
  fullName:undefined,
  isQuantity: undefined,
  medicalInsurCode: undefined,
  categoryId: undefined,
  unitId:undefined,
  wubiShortcode:undefined,
  batch:undefined,
  isDelete : 0,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const categoryList = ref<ProductCategoryVO[]>([]) // 产品分类列表
const unitList = ref<ProductUnitVO[]>([])//单位列表
const priceFormRef = ref() // 调价表单
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductApi.getProductPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
/**
 * 键入监听方法
 */
const hospitalFilter =(params)=> {
  //判断键入是否有值
  if(params!==""){
    //有值调用防抖方法
    debouncedSearch(params)
  }else{
    //没有键入值，集合为空
    supplierList.value=[]
  }
}
/**
 * 根据键入的值查询产品列表
 */
const productLists=async(params)=>{
  // 加载产品列表
  const supplierData = await ProductApi.getProductSimpleLists(params)
  supplierList.value = handleTree(supplierData, 'id')
}

 // 创建一个防抖函数来处理搜索操作
 const debouncedSearch =debounce((params,delay = 500) => { 
      //定义等待时间
      const timer = ref() 
      // 模拟异步数据获取（例如API调用）
      if(timer.value){
          //清除等待时间
          clearTimeout(timer.value); 
        }
      //等待时间赋值
      timer.value = setTimeout(async() => {
        //调用后端根据键入的值查询产品列表方法
        productLists(params)
      }, delay); // 延迟500毫秒以模拟网络延迟或数据处理时间
  }, 500); // 防抖等待时间为500毫秒   

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, dataId?: number) => {
  formRef.value.open(type, dataId)
}

const openPriceForm = (type: string, dataId?: number) => {
  priceFormRef.value.open(type, dataId)
}

/** 删除按钮操作 */
const handleDelete = async (dataId: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductApi.deleteProduct(dataId)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}




/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductApi.exportProduct(queryParams)
    download.excel(data, '产品.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 产品分类
  const categoryData = await ProductCategoryApi.getProductCategorySimpleList()
  categoryList.value = handleTree(categoryData, 'id', 'parentId')
  // 产品单位
  const unitData = await ProductUnitApi.getProductUnitSimpleList()
  unitList.value = handleTree(unitData, 'id')
})
</script>
